package uqbar.comm.netty.protocol;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

import uqbar.comm.netty.ProgramException;

/**
 * Convierte un objeto Output en un Array de bytes
 * 
 * @author leo
 * 
 */
public class ProtocolEncoder extends SimpleChannelHandler {

	private final Protocol protocol;

	public ProtocolEncoder(final Protocol protocol) {
		this.protocol = protocol;
	}

	@Override
	public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
		Object output = e.getMessage();
		ChannelBufferFactory channelFactory = this.getFactory(output);
		Channels.write(ctx, e.getFuture(), channelFactory.transform(output));
	}

	private ChannelBufferFactory getFactory(final Object output) {
		for (ChannelBufferFactory factory : this.protocol.getFactories()) {
			if (factory.canTransform(output)) {
				return factory;
			}
		}
		throw new ProgramException("No existe ninguna factory en el protocolo " + this.protocol + " para el output "
				+ output);
	}

}
